// 大学生智能消费记账系统 - 前端JavaScript功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initSidebar();
    initCharts();
    initForms();
    initNotifications();
});

// 侧边栏功能
function initSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const sidebarToggler = document.querySelector('.sidebar-toggler');

    if (sidebarToggler) {
        sidebarToggler.addEventListener('click', function() {
            sidebar.classList.toggle('show');
        });
    }

    // 移动端点击其他地方关闭侧边栏
    document.addEventListener('click', function(event) {
        if (window.innerWidth <= 768 && sidebar.classList.contains('show')) {
            if (!sidebar.contains(event.target) && !sidebarToggler.contains(event.target)) {
                sidebar.classList.remove('show');
            }
        }
    });
}

// 图表初始化
function initCharts() {
    // 消费趋势图
    const expenseChart = document.getElementById('expenseChart');
    if (expenseChart) {
        new Chart(expenseChart, {
            type: 'line',
            data: {
                labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                datasets: [{
                    label: '支出',
                    data: [650, 590, 800, 810, 890, 930],
                    borderColor: 'rgb(255, 99, 132)',
                    backgroundColor: 'rgba(255, 99, 132, 0.1)',
                    tension: 0.1,
                    fill: true
                }, {
                    label: '收入',
                    data: [1000, 1200, 1100, 1400, 1250, 1500],
                    borderColor: 'rgb(54, 162, 235)',
                    backgroundColor: 'rgba(54, 162, 235, 0.1)',
                    tension: 0.1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 消费分类饼图
    const categoryChart = document.getElementById('categoryChart');
    if (categoryChart) {
        new Chart(categoryChart, {
            type: 'doughnut',
            data: {
                labels: ['餐饮', '购物', '学习', '交通', '娱乐', '其他'],
                datasets: [{
                    data: [35, 25, 15, 10, 10, 5],
                    backgroundColor: [
                        '#FF6384',
                        '#36A2EB',
                        '#FFCE56',
                        '#4BC0C0',
                        '#9966FF',
                        '#FF9F40'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
}

// 表单验证和功能
function initForms() {
    // 密码确认验证
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            if (password !== confirmPassword) {
                e.preventDefault();
                showNotification('两次输入的密码不一致！', 'error');
                return false;
            }

            if (password.length < 6) {
                e.preventDefault();
                showNotification('密码长度至少为6位！', 'error');
                return false;
            }
        });
    }

    // 金额输入格式化
    const amountInputs = document.querySelectorAll('input[type="number"]');
    amountInputs.forEach(input => {
        input.addEventListener('blur', function() {
            if (this.value) {
                this.value = parseFloat(this.value).toFixed(2);
            }
        });
    });

    // 快速添加表单
    const quickAddForms = document.querySelectorAll('.quick-add-form');
    quickAddForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            // 这里可以添加AJAX提交逻辑
            showNotification('记录添加成功！', 'success');
            this.reset();
        });
    });
}

// 通知系统
function initNotifications() {
    window.showNotification = function(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 1050; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(notification);

        // 自动移除通知
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 5000);
    };
}

// 数据导出功能
function exportData(type) {
    let url = '';
    let filename = '';

    switch (type) {
        case 'income':
            url = '../export?type=income';
            filename = '收入记录.csv';
            break;
        case 'expense':
            url = '../export?type=expense';
            filename = '支出记录.csv';
            break;
        case 'budget':
            url = '../export?type=budget';
            filename = '预算记录.csv';
            break;
        default:
            return;
    }

    // 创建隐藏的下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showNotification('数据导出成功！', 'success');
}

// 搜索和过滤功能
function initSearchAndFilter() {
    const searchInputs = document.querySelectorAll('.search-input');
    const filterSelects = document.querySelectorAll('.filter-select');

    function performSearch() {
        const searchTerm = document.querySelector('.search-input')?.value.toLowerCase() || '';
        const filterValue = document.querySelector('.filter-select')?.value || '';

        const tableRows = document.querySelectorAll('tbody tr');

        tableRows.forEach(row => {
            const rowText = row.textContent.toLowerCase();
            const category = row.querySelector('.badge')?.textContent || '';

            const matchesSearch = rowText.includes(searchTerm);
            const matchesFilter = !filterValue || category === filterValue;

            row.style.display = (matchesSearch && matchesFilter) ? '' : 'none';
        });
    }

    searchInputs.forEach(input => {
        input.addEventListener('input', performSearch);
    });

    filterSelects.forEach(select => {
        select.addEventListener('change', performSearch);
    });
}

// 预算提醒功能
function checkBudgetAlerts() {
    const progressBars = document.querySelectorAll('.progress-bar');

    progressBars.forEach(bar => {
        const width = parseInt(bar.style.width);
        if (width >= 90) {
            bar.classList.add('bg-danger');
            const parentRow = bar.closest('tr');
            if (parentRow) {
                const statusCell = parentRow.querySelector('.budget-status');
                if (statusCell) {
                    statusCell.innerHTML += ' <i class="fas fa-exclamation-triangle text-danger"></i>';
                }
            }
        } else if (width >= 75) {
            bar.classList.add('bg-warning');
        }
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    initSearchAndFilter();
    checkBudgetAlerts();

    // 添加淡入动画
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
        card.style.animationDelay = `${index * 0.1}s`;
        card.classList.add('fade-in');
    });
});

// 工具函数
const Utils = {
    // 格式化金额
    formatCurrency: function(amount) {
        return '¥' + parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },

    // 格式化日期
    formatDate: function(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    },

    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 获取当前月份
    getCurrentMonth: function() {
        const now = new Date();
        return now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
    }
};

// 为全局使用暴露工具函数
window.Utils = Utils;
window.exportData = exportData;